﻿using System;
using System.IO;
using System.Reflection;
using System.Configuration;
using System.Diagnostics;
using System.Collections.Generic;
using Kyoh.App.Crawler.Contents;
namespace Kyoh.App.Crawler.Properties
{
    // このクラスでは設定クラスでの特定のイベントを処理することができます:
    //  SettingChanging イベントは、設定値が変更される前に発生します。
    //  PropertyChanged イベントは、設定値が変更された後に発生します。
    //  SettingsLoaded イベントは、設定値が読み込まれた後に発生します。
    //  SettingsSaving イベントは、設定値が保存される前に発生します。
    internal sealed partial class Settings
    {
        private string GetDirectoryPath(string directoryName)
        {
            var path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), directoryName);
            if (File.Exists(path))
                File.Delete(path);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path;
        }

        public static Dictionary<string, object> GetParams(Loader loader)
        {
            var para = new Dictionary<string, object>();
            para.Add(DirectoryParam, loader == null ? Strings.DirectoryParam : Path.GetDirectoryName(loader.FullPath));
            para.Add(FileNameParam, loader == null ? Strings.FileNameParam : loader.FullPath);
            para.Add(PageUriParam, loader == null ? Strings.PageUriParam : loader.Uri);
            para.Add(ContentUriParam, loader == null ? Strings.ContentUriParam : loader.ContentUri);
            return para;
        }

        public const string DirectoryParam = "Crawler.Directory";
        public const string FileNameParam = "Crawler.FileName";
        public const string PageUriParam = "Crawler.PageUri";
        public const string ContentUriParam = "Crawler.ContentUri";

        public const string DownloadPathMyDocuments = "<MyDocuments>";

        /// <summary>ダウンロード先のディレクトリのパスを取得します。</summary>
        public string DownloadPath
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_DownloadPath) || _DownloadPath == DownloadPathMyDocuments)
                    return GetMyDocumentsPath();
                else
                {
                    try
                    {
                        DirectoryInfo info = new DirectoryInfo(_DownloadPath);
                        if (info.Exists == false)
                            return GetMyDocumentsPath();
                        else
                            return info.FullName;
                    }
                    catch(Exception exc)
                    {
                        Debug.WriteLine(exc);
                        return GetMyDocumentsPath();
                    }
                }
            }
        }

        private static string GetMyDocumentsPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }

        public Settings()
        {
            // // 設定の保存と変更のイベント ハンドラーを追加するには、以下の行のコメントを解除します:
            //
            this.SettingChanging += this.SettingChangingEventHandler;
            this.SettingsSaving += this.SettingsSavingEventHandler;
            this.SettingsLoaded += this.SettingsLoadedEventHandler;
            //
        }

        private bool loaded = false;

        private void SettingsLoadedEventHandler(object sender, SettingsLoadedEventArgs e)
        {
            this["SeekerPath"] = this.GetDirectoryPath("seeker");
            this["ParserPath"] = this.GetDirectoryPath("parser");
            this["RedirectPath"] = this.GetDirectoryPath("redirect");
            this["PickerPath"] = this.GetDirectoryPath("picker");
            this.loaded = true;
        }

        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
        {
            switch (e.SettingName)
            {
                case "SeekerPath":
                    e.Cancel = this.loaded;
                    break;
                case "ParserPath":
                    e.Cancel = this.loaded;
                    break;
                case "RedirectPath":
                    e.Cancel = this.loaded;
                    break;
                case "PickerPath":
                    e.Cancel = this.loaded;
                    break;
            }
        }

        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this["SeekerPath"] = this.GetDirectoryPath("seeker");
            this["ParserPath"] = this.GetDirectoryPath("parser");
            this["RedirectPath"] = this.GetDirectoryPath("redirect");
            this["PickerPath"] = this.GetDirectoryPath("picker");
            if (DownloadPath == GetMyDocumentsPath())
                _DownloadPath = DownloadPathMyDocuments;
            else
                _DownloadPath = DownloadPath;
        }
    }
}